<?php

namespace app\api\controller\permission;

use app\api\controller\common\ApiBase;
use app\api\model\AdminRole as AdminRoleModel;
use app\api\model\Role as RoleModel;
use app\api\model\RoleAuth as RoleAuthModel;
use app\api\model\Auth as AuthModel;
use think\Db;

class Role extends ApiBase
{

    /**
     * 查看角色
     *
     * @return void
     */
    public function index()
    {
        if (request()->isPost()) {
            $roleList = RoleModel::field('id,role_name,is_gl,status,create_time,update_time')->with('auth')->select();
            $authList = AuthModel::field('id,auth_name,status,rule,parent_id,sort,create_time,update_time')->select();
            $authList = collection($authList)->toArray();
            foreach ($authList as $k => $v) {
                //除了超管，其他的管理员不应该有权限管理的权限
                if (strpos($v['rule'], 'permission') !== false) {
                    unset($authList[$k]);
                }
            }
            $authList = list_to_tree($authList);
            return json(array('code' => '1', 'msg' => '成功', 'data' => ['roleList' => $roleList, 'authList' => $authList]));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 新增角色
     *
     * @return void
     */
    public function add()
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $role = new RoleModel();
                $data['role_name'] = isset($post['role_name']) && $post['role_name'] != '' ? $post['role_name'] : '';
                $data['status'] = isset($post['status']) && $post['status'] != '' ? $post['status'] : 0;
                $data['is_gl'] = isset($post['is_gl']) && $post['is_gl'] != '' ? $post['is_gl'] : 0;
                $result = $role->validate('Role.add')->save($data);
                if (false === $result) {
                    $msg = $role->getError();
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => $msg));
                } else {
                    if (!empty($post['auth_ids'])) {
                        $post['auth_ids'] = explode(',', $post['auth_ids']);
                        $role->auth()->save($post['auth_ids']);
                    }
                    Db::commit();
                    return json(array('code' => '1', 'msg' => '成功'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 编辑角色
     *
     * @return void
     */
    public function edit()
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $post = input('post.');
                $id = $post['id'];
                $role = RoleModel::get($id);
                $data['role_name'] = isset($post['role_name']) && $post['role_name'] != '' ? $post['role_name'] : '';
                $data['status'] = isset($post['status']) && $post['status'] != '' ? $post['status'] : 0;
                $data['is_gl'] = isset($post['is_gl']) && $post['is_gl'] != '' ? $post['is_gl'] : 0;
                $result = $role->validate('Role.edit')->save($data);
                if (false === $result) {
                    $msg = $role->getError();
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => $msg));
                } else {
                    RoleAuthModel::where(['role_id' => $id])->delete();
                    if (!empty($post['auth_ids'])) {
                        $post['auth_ids'] = explode(',', $post['auth_ids']);
                        $role->auth()->save($post['auth_ids']);
                    }
                    Db::commit();
                    return json(array('code' => '1', 'msg' => '成功'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 删除角色
     *
     * @return void
     */
    public function del()
    {
        if (request()->isPost()) {
            Db::startTrans();
            try {
                $id = input('post.id');
                $adminRole = AdminRoleModel::where(['role_id' => $id])->find();
                if ($adminRole) {
                    return json(array('code' => '0', 'msg' => '已有管理员绑定此角色，不能直接删除'));
                }
                $role = RoleModel::get($id);
                $result = $role->delete();
                if (false === $result) {
                    $msg = $role->getError();
                    Db::rollback();
                    return json(array('code' => '0', 'msg' => $msg));
                } else {
                    RoleAuthModel::where(['role_id' => $id])->delete();
                    Db::commit();
                    return json(array('code' => '1', 'msg' => '成功'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                return json(array('code' => '0', 'msg' => $e->getMessage()));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }
}
